const Collect = require("../model/collect.model");
// 使用模糊查询需要先引入Op
const seq = require("sequelize");
const Op = seq.Op;
const User = require("../model/user.model");
const Information = require("../model/information.model");
const Category = require("../model/category.model");
class CollectService {
  /**
   * 创建
   * @returns {Promise<{code: string, message: string}>}
   * @param collect
   */
  async createCollect(collect) {
    const res = await Collect.create(collect);
    return res.dataValues;
  }

  /**
   * 更新
   * @param id
   * @param collect
   * @returns {Promise<boolean>}
   */
  async updateCollect(id, collect) {
    const res = await Collect.update(collect, { where: { id } });
    return res[0] > 0;
  }

  /**
   * 删除
   * @returns {Promise<boolean>}
   * @param id
   */

  async removeCollect(id) {
    const res = await Collect.destroy({ where: { id }});
    return res > 0;
  }

  /**
   * 恢复
   * @param id
   * @returns {Promise<boolean>}
   */

  async restoreCollect(id) {
    const res = await Collect.restore({ where: { id } });
    return res > 0;
  }

  async findCollect({ pageNum, pageSize,user_id,type }) {
    const offset = (pageNum - 1) * pageSize;
    const whereOpt1 = {};
    console.log(type,"typetypetype")
    if(type === 1){
      Object.assign(whereOpt1, {
        info_id: {
            [Op.ne]: null,
        }
      });

    }else{
        Object.assign(whereOpt1, {
            cat_id: {
                [Op.ne]: null,
            }
        });
    }
    user_id && Object.assign(whereOpt1, { user_id });

    console.log(whereOpt1,"whereOpt1")
    const { count, rows } = await Collect.findAndCountAll({
      offset: offset,
      limit: pageSize * 1,
      where: whereOpt1,
      include:[
        {
          model: Category,
          as: "category_info",
        },
        {
          model: Information,
          as: "information_info",
        }
      ],
      order: [["createdAt", "DESC"]],
    });

    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }

  async findCollectInfo(id) {
    const whereOpt = {};
    id && Object.assign(whereOpt, { id });

    const res = await Collect.findOne({
      where: whereOpt,
    });

    return res ? res.dataValues : null;
  }

  async findIsCollect({info_id,user_id,cat_id}) {
    const whereOpt = {};
    info_id && Object.assign(whereOpt, { info_id });
    user_id && Object.assign(whereOpt, { user_id });
    cat_id && Object.assign(whereOpt, { cat_id });

    const res = await Collect.findOne({
      where: whereOpt,
    });

    return res ? res.dataValues : null;
  }
}

module.exports = new CollectService();
